<template>
  <div>
    <!-- 面包屑导航区： -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮: -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showDialog('add')">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolelist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom',index===0?'bdtop':'','flex-center']"
              :gutter="20"
              v-for="(tag,index) in scope.row.children"
              :key="tag.id"
            >
              <!-- 渲染一级权限： -->
              <el-col :span="5">
                <el-tag
                  closable
                  :disable-transitions="false"
                  @close="removeRightsTagById(scope.row,tag.id)"
                >{{tag.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级权限： -->
              <el-col :span="19">
                <!-- 通过for循环嵌套渲染二级权限 -->
                <el-row
                  v-for="(lv2tag,lv2index) in tag.children"
                  :key="lv2tag.id"
                  :class="[lv2index===0?'':'bdtop','flex-center']"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      :disable-transitions="false"
                      type="success"
                      @close="removeRightsTagById(scope.row,lv2tag.id)"
                    >{{lv2tag.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 再for循环渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      closable
                      :disable-transitions="false"
                      type="warning"
                      v-for="lv3tag in lv2tag.children"
                      :key="lv3tag.id"
                      @close="removeRightsTagById(scope.row,lv3tag.id)"
                    >{{lv3tag.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showDialog('edit',scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRole(scope.row.id)"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialog" width="50%" @close="rightDialogClose">
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialog = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加/编辑角色对话框 -->
    <el-dialog :title="DialogTitle" :visible.sync="rolesDialog" width="50%" @close="hideDialog">
      <el-form :model="addPartForm" :rules="addPartFormRules" ref="addPartForm" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addPartForm.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addPartForm.roleDesc" type="textarea" :rows="2" placeholder="请输入角色描述"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="rolesSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rolelist: [],
      // 所有权限列表
      rightsList: [],
      // 控制分配权限对话框显示和隐藏
      setRightDialog: false,
      // 实现父子嵌套的标签和属性：
      treeProps: {
        label: "authName",
        children: "children"
      },
      // 默认勾选的节点的id值数组,在展开分配权限的时候把当前项的三级权限 id传递进去
      defKeys: [],
      // 即将分配权限的id:
      roleId: "",
      // 添加角色弹框
      rolesDialog: false,
      // 添加角色表单数据
      addPartForm: {
        roleName: "",
        roleDesc: ""
      },
      addPartFormRules: {
        roleName: [
          {
            required: true,
            message: "请输入角色名称",
            trigger: "blur"
          },
          {
            min: 1,
            max: 10,
            message: "角色名称的长度在 1 到 10 个字符之间",
            trigger: "blur"
          }
        ]
      },
      // 弹框标题：
      DialogTitle: "",
      // 弹框种类add:新增,edit:编辑：
      Dialogtype: "",
      // 编辑弹框的id:
      editroleId: ""
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    //   获取所有角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("/roles");
      this.rolelist = res.data;
    },
    // 根据tagid删除权限
    async removeRightsTagById(role, rightId) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (confirmResult !== "confirm") {
        return this.$message.info("取消删除");
      } else {
        this.$http.delete(`roles/${role.id}/rights/${rightId}`).then(res => {
          this.$message.success("删除权限成功");
          // this.getRolesList();
          // 直接赋值给当前列表的children防止页面刷新
          role.children = res.data.data;
        });
      }
    },
    // 展示分配权限的对话框
    async showSetRightDialog(node) {
      this.roleId = node.id;

      // 获取全部权限数据
      const { data: res } = await this.$http.get("rights/tree");
      this.rightsList = res.data;
      this.setRightDialog = true;
      this.getLeafKeys(node, this.defKeys);
    },
    // 递归获取全部角色下三级权限的id
    getLeafKeys(node, arr) {
      // 如果当前node节点下不包含chidren属性，则把他的id直接传递给数组
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach(item => this.getLeafKeys(item, arr));
    },
    // 关闭分配权限的对话框
    rightDialogClose() {
      this.defKeys = [];
      this.setRightDialog = false;
    },
    // 点击重新给选定角色分配权限
    async allotRights() {
      // 获取已选中节点的id数组 和 半选中节点的id数组
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      const idStr = keys.join(",");
      const { data: res } = await this.axios.post(
        `roles/${this.roleId}/rights`,
        {
          rids: idStr
        }
      );
      console.log(res);

      if (res.meta.status !== 200) {
        return this.$message.error("分配权限失败");
      }
      this.$message.success("分配权限成功!");
      this.getRolesList();
      this.setRightDialog = false;
    },
    // 角色列表页面弹框
    showDialog(type, info) {
      this.rolesDialog = true;
      if (type === "add") {
        this.DialogTitle = "添加角色";
        this.Dialogtype = "add";
        this.addPartForm = {};
        this.editroleId = "";
      } else if (type === "edit") {
        this.DialogTitle = "修改角色";
        this.Dialogtype = "edit";
        let editinfo = JSON.parse(JSON.stringify(info));
        this.addPartForm = editinfo;
        this.editroleId = info.id;
      }
    },
    // 隐藏弹框：
    hideDialog() {
      this.addPartDialog = false;
    },
    // 添加角色按钮点击
    rolesSubmit() {
      this.$refs.addPartForm.validate(valid => {
        // 表单校验失败
        if (!valid) {
          return;
        }
        let methods, url, params;
        // 新增请求：
        if (this.Dialogtype === "add") {
          methods = "post";
          url = "/roles";
        } else if (this.Dialogtype === "edit") {
          methods = "put";
          url = `/roles/${this.editroleId}`;
        }
        params = this.addPartForm;
        this.$http[methods](url, params).then(res => {
          if (this.Dialogtype === "add") {
            this.$message.success("创建角色成功");
          } else if (this.Dialogtype === "edit") {
            this.$message.success("更新角色成功");
          }
          this.getRolesList();
          this.rolesDialog = false;
          this.$refs.addPartForm.resetFields();
        });
      });
    },
    // 删除角色弹框：
    deleteRole(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http.delete(`/roles/${id}`).then(res => {
            this.$message.success("删除用户成功");
            this.getRolesList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  }
};
</script>
<style lang="less" scope>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.flex-center {
  display: flex;
  align-items: center;
}
</style>